<?php
/**
 * description
 *
 * @category   Es字段
 * @package    PSR
 * @subpackage Documentation\API
 * @author     weiyizheng
 * @date       2022/11/8
 * @time       4:39 下午
 */

namespace Buu\Modules\EsStandard\Controllers;


use App\Http\Controllers\Controller;
use App\Models\EsColumn;
use App\Models\EsColumnBindShip;
use Illuminate\Http\Request;

class EsColumnController extends Controller
{
	public function save(Request $request, $id)
	{
		$res = $request->all();
		$newData = [];
		$delData = [];
		foreach ($res['column'] as $k => $v) {
			$data = [
				'es_index_id' => $id,
				'column_name' => $v['column_name'] ?? '',
				'column_type' => $v['column_type'] ?? '',
				'column_is_index' => $v['column_is_index'] ?? 0,
				'column_is_keyword' => $v['column_is_keyword'] ?? 0,
				'is_primary' => $v['is_primary'] ?? 0,
			];
			if ($v['_remove_'] == 1) {
				$delData[] = $v['id'];
				continue;
			}
			if ($v['id'] == '') {
				$newData[] = $v;
				continue;
			}
			EsColumn::query()->where('id', $v['id'])->update($data);

			// 更新绑定
			if (!empty($v['db_tables_id']) && !empty($v['source_column_name'])) {
				$bindData = [
					'es_column_id' => $v['id'],
					'es_index_id' => $id,
					'db_tables_id' => $v['db_tables_id'] ?? 0,
					'source_column_name' => $v['source_column_name'] ?? '',
					'bind_type' => $v['bind_type'] ?? 0,
				];
				if ($v['bind_id']) {
					EsColumnBindShip::query()->where('id', $v['bind_id'])->update($bindData);
				} else {
					EsColumnBindShip::query()->insert($bindData);
				}
			}
		}
		if ($delData) {
			EsColumn::query()->whereIn('id', $delData)->delete();
			EsColumnBindShip::query()->whereIn('es_column_id', $delData)->delete();
		}
		// 处理新增
		if ($newData) {
			foreach ($newData as $value) {
				$data = [
					'es_index_id' => $id,
					'column_name' => $value['column_name'] ?? '',
					'column_type' => $value['column_type'] ?? '',
					'column_is_index' => $value['column_is_index'] ?? 0,
					'column_is_keyword' => $value['column_is_keyword'] ?? 0,
					'is_primary' => $value['is_primary'] ?? 0,
				];
				$cid = EsColumn::query()->insertGetId($data);
				$bindData = [
					'es_column_id' => $cid,
					'es_index_id' => $id,
					'db_tables_id' => $value['db_tables_id'] ?? 0,
					'source_column_name' => $value['source_column_name'] ?? '',
					'bind_type' => $value['bind_type'] ?? 0,
				];
				EsColumnBindShip::query()->insert($bindData);
			}
		}

		$msg = '编辑成功';

		admin_toastr($msg, 'success', ['timeOut' => 3]);
		return redirect('/admin/EsStandard/es-index/' . $id . '/column/edit#tab_column');
	}
}